import { createRouter, createWebHistory } from 'vue-router'
import { store } from '@/common/store'
import HomeView from '../views/HomeView.vue'

const router = createRouter({
  history: createWebHistory(import.meta.env.BASE_URL),
  routes: [
    {
      path: '/',
      redirect: "login",
    },
    {
      path: '/login',
      component: () => import('@/views/LoginPage.vue')
    },
    {
      path: '/register',
      component: () => import('@/views/RegisterView.vue')
    },
    {
      path: '/index', 
      component: () => import('@/views/IndexPage.vue'),
      meta: { requiresAuth: true },
      children: [
        {
          path: "",
          redirect: "/index/products"
        },
        {
          path: 'admin',
          component: () => import('@/views/AdminView.vue')
        },
        {
          path: 'products',
          component: () => import('@/views/ProductsView.vue')
        },
        {
          path: 'userinfo',
          component: () => import('@/views/UserInfoView.vue')
        },
        {
          path: 'info-control',
          component: () => import('@/views/InfoControl.vue')
        },
        {
          path: 'product-data',
          component: () => import('@/views/ProductData.vue')
        },
        {
          path: 'appoint',
          component: () => import('@/views/AppointView.vue')
        },
        {
          path: 'auth',
          component: () => import('@/views/AuthView.vue')
        }
      ]
    },
  ],
})

router.beforeEach((to, from, next) => {
  if (to.meta.requiresAuth) {
    // 检查store中的登录状态和token
    if (!store.logined || !store.token) {
      next('/login')
      return
    }
  }
  next()
})

export default router
